<template>
    <div class="page">
      <van-nav-bar :title="pageTitle"></van-nav-bar>
      <van-cell-group>
        <van-field
          v-model="user"
          @blur="handleUserBlur"
          label="用户名"
          placeholder="请输入用户名"
          :error-message="userErrorMessage"
          error-message-align="left"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="pass"
          @blur="handlePassBlur"
          label="密码"
          placeholder="请输入密码"
          :error-message="passErrorMessage"
          error-message-align="left"
        />
      </van-cell-group>
      <van-button :type="type" class="button" @click="fn">{{ pageButton }}</van-button>
    </div>
  </template>
  
  <script>
  export default {
    props: {
      pageTitle: {
        type: String,
        default: "登录",
      },
      pageButton: {
        type: String,
        default: "提交",
      },
      type: {
        type: String,
        default: "primary",
      },
    },
    data() {
      return {
        user: "",
        pass: "",
        userErrorMessage: "",
        passErrorMessage: "",
      };
    },
    methods: {
      fn() {
        if (this.user.trim() === "") {
          this.userErrorMessage = "请输入用户名";
          return;
        }
        if (this.user.trim().length < 6) {
          this.userErrorMessage = "用户名至少6个字符";
          return;
        }
        if (this.pass.trim() === "") {
          this.passErrorMessage = "请输入密码";
          return;
        }
        if (this.pass.trim().length < 6) {
          this.passErrorMessage = "密码至少6个字符";
          return;
        }
        this.$emit("login", this.user, this.pass);
      },
      handleUserBlur() {
        if (this.user.trim() === "") {
          this.userErrorMessage = "请输入用户名";
        } else if (this.user.trim().length < 6) {
          this.userErrorMessage = "用户名至少6个字符";
        } else {
          this.userErrorMessage = "";
        }
      },
      handlePassBlur() {
        if (this.pass.trim() === "") {
          this.passErrorMessage = "请输入密码";
        } else if (this.pass.trim().length < 6) {
          this.passErrorMessage = "密码至少6个字符";
        } else {
          this.passErrorMessage = "";
        }
      },
    },
  };
  </script>
  
  <style lang="less" scoped>
  .page {
    .button {
      margin-top: 20px;
      width: 90%;
      margin-left: 5%;
    }
  }
  </style>
